import { pageConfig } from '../lib/config.js';
import { caishui } from '../lib/caishui.js';
import { getTaxConfig } from './utils.js';

// 缓存pageConfig 供content.js 使用
caishui.setLocal({ pageConfig: pageConfig }, function(e) {
  console.log('page config success');
});


chrome.runtime.onMessageExternal.addListener(function(
  { message, data },
  sender,
  sendResponse
) {
  if (message) {
    // 版本信息提供
    if (message === 'version') {
      let manifest = chrome.runtime.getManifest();
      let version = manifest.version;
      sendResponse({ version });
    }
    // 该城市能否同步申报表
    if (message === 'canSyncReport') {
      const { cityName, provName } = data || {};
      let currentCity = getTaxConfig({ cityName, provName });
      currentCity = currentCity && currentCity[0];
      sendResponse(!!(currentCity || {}).isSupportSyncDeclareType);
    }
  }
});

// page action， 在配置列表url才显示插件
chrome.runtime.onInstalled.addListener(function() {
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    let conditions = [];
    pageConfig.forEach(function(item) {
      if (item.urlContains) {
        item.urlContains.forEach(function(url) {
          conditions.push(
            new chrome.declarativeContent.PageStateMatcher({
              pageUrl: { urlContains: url }
            })
          );
        });
      }
    });
    chrome.declarativeContent.onPageChanged.addRules([
      {
        conditions: conditions,
        actions: [new chrome.declarativeContent.ShowPageAction()]
      }
    ]);
  });
});
